<template>
    <div class="all-container flex" :class="{ closeSide: !open, horizontal: horizontal }">
        <side-bar class="aside-container" :collapsed="open" v-if="!horizontal" />
        <div class="main-container" :class="{ hasTag: tagShow }">
            <div class="fixed-header">
                <nav-bar :collapsed="open" v-if="!horizontal" />
                <div v-else class="horizontal-nav flex">
                    <horizontal-side />
                    <nav-bar :horizontal="horizontal" class="nav-user"></nav-bar>
                </div>
                <tag-view v-if="tagShow" />
            </div>
            <div v-if="initSetting" class="rightPanl fixed pointer" @click="changeVisivle">
                <a-icon type="setting" class="settingIcon" />
                <setting />
            </div>
            <scroll-bar class="app-main">
                <router-view v-if="isRouterAlive" />
                <back-top />
            </scroll-bar>
            <p class="company-info">{{companyName}}</p>
        </div>
    </div>
</template>

<script>
import { sideBar, navBar, tagView, setting, horizontalSide } from './components';
import backTop from '@/components/backTop/index';
import { mapState } from 'vuex';
import {companyName} from '@/utils/config'

import mqtt from 'mqtt';

export default {
    name: 'layout',
    components: { sideBar, navBar, tagView, setting, backTop, horizontalSide },
    inject: ['playAudio'],
    data() {
        return {
            companyName,
            mtopic: 'realtime',
            // mtopic: '+/+',
            msg: '',
            client: {},
            isRouterAlive:true
        };
    },
    created() {
        this.connectMqtt();
        // let item = '您好，您所管理的编号为864999041099274的液位检测设备，发生低限报警，当前报警值为34';
        // setTimeout(()=>{
        //     this.playAudio(item, '1_alarm');
        // },2000)
    },
    watch:{
        tenant:function(e){
            this.refreshMain();
        }
    },
    computed: {
        ...mapState({
            open: state => state.setting.open,
            fixHeader: state => state.setting.fixHeader,
            tagShow: state => state.setting.tagShow,
            layout: state => state.setting.layout,
            initSetting: state => state.setting.initSetting,
            accountInfo: state => state.user.accountInfo,
            tenant:state=>state.user.tenant
        }),
        horizontal() {
            return this.layout == 'horizontal';
        }
    },
    methods: {
        //刷新页面主体 重新发起请求
        refreshMain(){
            this.isRouterAlive = false
            this.$nextTick(function() {
                this.isRouterAlive = true
            })
        },
        changeVisivle() {
            this.$store.dispatch('setting/changeVisible', true);
        },
        //连接mqtt
        connectMqtt() {
            let time = new Date().getTime();
            let {userName,userId} = this.accountInfo;
            const options = {
                clean: true, // 保留回话
                connectTimeout: 4000, // 超时时间
                reconnectPeriod: 4000, // 重连时间间隔
                //clientId,这个是EMQ Dashboard的上的clientId 对应就好
                // clientId: '865771056124183',
                clientId: userName+'-'+time,
                username: 'admin',
                password: 'public'
            };
            this.client = mqtt.connect(`ws://118.195.176.189:8083/mqtt`, options);
            this.client.on(
                'connect',
                e => {
                    this.client.subscribe(`${userId}_alarm`, err => {
                        if (!err) {
                            console.log('订阅成功:报警主题');
                        }
                    });
                    this.client.subscribe(`${userId}_notice`, err => {
                        if (!err) {
                            console.log('订阅成功:通知主题');
                        }
                    });
                    // if(roleCode=='superAdmin'){
                    //     this.client.subscribe('auth', err => {
                    //         if (!err) {
                    //             console.log('订阅成功:认证主题');
                    //         }
                    //     });
                    // }
                },
                err => {
                    console.log(err);
                }
            );
            this.client.on('message', (topic, message) => {
                if(!userId){
                    this.clearMqtt();
                    return false;
                }
                this.refreshMain();
                let item = this.Uint8ArrayToString(message);
                // let data = null;
                // if(item.indexOf('messageId')==-1){
                //     let time = new Date().getTime();
                //     data = {
                //         message:item,
                //         deviceCode:time,
                //         messageId:time,
                //     }
                // }else{
                //     data = JSON.parse(item);
                // }
                // data = JSON.parse(item);
                if (item) {
                    this.playAudio(item, topic);
                }
            });
        },
        Uint8ArrayToString(array) {
            var out, i, len, c;
            var char2, char3;

            out = '';
            len = array.length;
            i = 0;
            while (i < len) {
                c = array[i++];
                switch (c >> 4) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                        // 0xxxxxxx
                        out += String.fromCharCode(c);
                        break;
                    case 12:
                    case 13:
                        // 110x xxxx 10xx xxxx
                        char2 = array[i++];
                        out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
                        break;
                    case 14:
                        // 1110 xxxx 10xx xxxx 10xx xxxx
                        char2 = array[i++];
                        char3 = array[i++];
                        out += String.fromCharCode(((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0));
                        break;
                }
            }

            return out;
        },
        //清除mqtt连接
        clearMqtt(){
            if (this.client.connected) {
                try {
                    this.client.end();
                    this.client = {
                        connected: false
                    };
                    console.log('Successfully disconnected!');
                } catch (error) {
                    console.log('Disconnect failed', error.toString());
                }
            }
        }
    },
    beforeDestroy() {
        this.clearMqtt();
    }
};
</script>
<style lang="scss" scoped>
$leftSide: 186px;
.all-container {
    flex-direction: row;
}

.aside-container {
    flex-shrink: 0;
    background: $menu-bg;
    transition: width 0.28s;
    width: $leftSide;
    height: 100vh; // position: fixed;
    // top: 0;
    // left: 0;
    // z-index: 996;
    // height: 100%;
}

.main-container {
    flex: 1;
    flex-shrink: 1;
    height: 100vh; // width: calc(100% - 186px);
    // margin-left: $leftSide;
    display: flex;
    flex-direction: column;
    .fixed-header {
        position: fixed;
        top: 0;
        right: 0;
        z-index: 996;
        transition: width 0.28s;
        width: calc(100% - 186px);
        & ~ .app-main {
            flex: 1;
            overflow: hidden;
            margin-top: 100px; // padding-top: 54px;
            // min-height: 100vh;
        }
    }
    .paddingBox-container {
        min-height: calc(100vh - 54px);
    }
}

.hasTag {
    .fixed-header {
        & ~ .app-main {
            flex: 1;
            overflow: hidden;
        }
    }
    .paddingBox-container {
        min-height: calc(100vh - 176px);
    }
}

.closeSide {
    .aside-container {
        width: 80px;
    }
    .main-container {
        // width: calc(100% - 80px);
        // margin-left: 80px;
    }
    .fixed-header {
        width: calc(100% - 80px);
    }
}
.company-info {
    position: relative;
    height: 28px;
    line-height: 28px;
    font-size: 12px;
    color: #999;
    text-align: center;
    box-shadow: 0 -1px 2px rgba($color: #000000, $alpha: .03);
    z-index: 9;
}
.rightPanl {
    right: 1px;
    top: 300px;
    transform: translateY(-50%);
    width: 50px;
    height: 50px;
    color: #fff;
    background: #4165d7;
    border-radius: 6px 0 0 6px;
    text-align: center;
    line-height: 50px;
    font-size: 24px;
    z-index: 999;
}

.app-main {
    height: calc(100vh - 100px);
    ::v-deep .scrollbar__view {
        width: 100%;
        min-height: 100%;
        padding: 20px;
        background: #edeff7;
    }
}

//水平布局
.horizontal {
    .aside-container {
        width: 0;
    }
    .horizontal-nav {
        background: #293348;
        color: #f1f1f1;
        height: 54px;
        line-height: 54px;
    }
    .main-container {
        width: 100%;
        margin-left: 0;
    }
    .fixed-header {
        width: 100%;
    }
    .nav-user {
        background: #293348;
    }
    .app-main {
        width: 100%;
        box-sizing: border-box;
        padding: 0 6%;
        background: #f0f2f5;
    }
}
</style>
